<template>
  <div class="c-fft3q2">
    <NavBar :isShowLeft="false">
      <template slot="left">
        <van-icon name="arrow-left" @click="handleBack" />
      </template>
      <template slot="content">
        <div>{{ title }}</div>
      </template>
    </NavBar>
    <Loading :loading="loading">
      <div class="c-fft3q2-main">
        <div v-if="type === 'card'">
          <div class="c-fft3q2-item">
            <div class="c-fft3q2-item-title">身份证正面识别</div>
            <div
              class="c-fft3q2-item-content"
              @click="
                show = true
                idImageType = 'front'
              "
            >
              <div v-if="upFileList.length == 0">
                <img src="./img/card2.png" class="c-fft3q2-item-content-img" />
                <div class="c-fft3q2-item-content-text">
                  拍摄上传身份证人像面
                </div>
              </div>
              <div v-else class="c-lnqk5r">
                <img class="c-lnqk5r-img" :src="upFileList[0].content" />
                <div class="c-lnqk5r-text">点击重新拍摄上传</div>
              </div>
            </div>
          </div>
          <div class="c-fft3q2-item">
            <div class="c-fft3q2-item-title">身份证反面识别</div>
            <div
              class="c-fft3q2-item-content"
              @click="
                show = true
                idImageType = 'back'
              "
            >
              <div v-if="downFileList.length == 0">
                <img src="./img/card1.png" class="c-fft3q2-item-content-img" />
                <div class="c-fft3q2-item-content-text">
                  拍摄上传身份证国徽面
                </div>
              </div>
              <div v-else class="c-lnqk5r">
                <img class="c-lnqk5r-img" :src="downFileList[0].content" />
                <div class="c-lnqk5r-text">点击重新拍摄上传</div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="type === 'bank'">
          <div class="c-fft3q2-item">
            <div class="c-fft3q2-item-title">银行卡正面扫描</div>
            <div class="c-fft3q2-item-content" @click="show = true">
              <div v-if="bankFileList.length == 0">
                <img src="./img/bankbg.png" class="c-fft3q2-item-content-img" />
                <img
                  src="./img/bankcenter.png"
                  class="c-fft3q2-item-content-img-c"
                />
                <div class="c-fft3q2-item-content-text">拍摄银行卡正面</div>
              </div>
              <div v-else class="c-lnqk5r">
                <img class="c-lnqk5r-img" :src="bankFileList[0].content" />
                <div class="c-lnqk5r-text">点击重新拍摄上传</div>
              </div>
            </div>
          </div>
        </div>
        <div class="c-fft3q2-img-list">
          <div class="c-fft3q2-img-list-title">
            拍摄时确保证件
            <span class="c-fft3q2-img-list-title-txt">
              边框完整，字体清晰，亮度均匀
            </span>
          </div>
          <div class="flex-row flex-align-center">
            <div class="c-fft3q2-img-list-item">
              <div class="c-fft3q2-img-list-item-big">
                <img src="./img/good.png" />
              </div>
              <div class="c-fft3q2-img-list-item-small">
                <img src="./img/good1.png" />
              </div>
              <div class="c-fft3q2-img-list-item-txt">标准</div>
            </div>
            <div class="c-fft3q2-img-list-item">
              <div class="c-fft3q2-img-list-item-big">
                <img src="./img/bad1.png" />
              </div>
              <div class="c-fft3q2-img-list-item-small">
                <img src="./img/error.png" />
              </div>
              <div class="c-fft3q2-img-list-item-txt">边角缺失</div>
            </div>
            <div class="c-fft3q2-img-list-item">
              <div class="c-fft3q2-img-list-item-big">
                <img src="./img/bad2.png" />
              </div>
              <div class="c-fft3q2-img-list-item-small">
                <img src="./img/error.png" />
              </div>
              <div class="c-fft3q2-img-list-item-txt">对焦模糊</div>
            </div>
            <div class="c-fft3q2-img-list-item">
              <div class="c-fft3q2-img-list-item-big">
                <img src="./img/bad3.png" />
              </div>
              <div class="c-fft3q2-img-list-item-small">
                <img src="./img/error.png" />
              </div>
              <div class="c-fft3q2-img-list-item-txt">闪光强烈</div>
            </div>
          </div>
        </div>
        <div
          class="c-fft3q2-bottom"
          :class="handleColor()"
          @click="handleClick"
        >
          确定
        </div>

        <!-- <input type="file" id="fileInput" /> -->
      </div>

      <!-- 显示上传方式 -->
      <van-popup v-model="show" position="bottom" class="c-fft3q2-pop">
        <van-uploader
          class="c-fft3q2-pop-item flex-row flex-align-center flex-justify-center"
          :max-count="1"
          :after-read="afterRead"
          name="picture"
          accept="image/*"
        >
          <img src="./img/photo.png" />
          <span>相册上传</span>
        </van-uploader>
        <van-uploader
          v-if="!isAndroid"
          class="c-fft3q2-pop-item flex-row flex-align-center flex-justify-center"
          :max-count="1"
          capture="camera"
          name="camera"
          :after-read="afterRead"
        >
          <img src="./img/camera.png" />
          <span>拍摄上传</span>
        </van-uploader>
        <div
          v-if="isAndroid"
          class="c-fft3q2-pop-item flex-row flex-align-center flex-justify-center"
          @click="handleCamera"
        >
          <img src="./img/camera.png" />
          <span>拍摄上传</span>
        </div>
        <div
          class="c-fft3q2-pop-item flex-row flex-align-center flex-justify-center"
        >
          <span @click="show = false">取消</span>
        </div>
      </van-popup>
    </Loading>
  </div>
</template>
<script>
import NavBar from '@/components/h5header'
import API from '@/services/h5/product'
import { mapState, mapMutations } from 'vuex'
import Loading from '@/components/data-loading'

import { JsBridge } from '@/utils/jsBridge'
import { isAndroid } from '@/utils/platform'
import takeCamera from '@/services/h5/app-api/takeCamera.js'
export default {
  components: { NavBar, Loading },
  data() {
    return {
      isAndroid,
      type: '', // 类型
      title: '', // navbar标题
      upFileList: [],
      downFileList: [],
      bankFileList: [],
      idImageType: '', // 证件正反面：front为正人头面，back为国徽面
      show: false,
      result: {
        isIdLongTerm: '',
        idEndDate: '',
        birthday: '',
        chnName: '',
        fileInfoId: '',
        idNo: '',
        idType: '',
        sex: ''
      },
      bankInfo: {
        bankId: '',
        cardNo: '',
        fileInfoId: ''
      },
      fromPage: null,
      fileInfoIdList: []
    }
  },
  computed: {
    ...mapState('loading', ['loading'])
  },
  created() {
    let _that = this
    JsBridge.registerHandler('cameraBack', function (data, callback) {
      console.log('========================picture.data=========', data)
      let jsonData = JSON.parse(data)
      let imgData =
        'data:image/png;base64,' + jsonData.base64image.replace(/[\r\n]/g, '')
      let arr = imgData.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let suffix = mime.split('/')[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      let compressImg = new File([u8arr], `${'file'}.${suffix}`, {
        type: mime
      })
      _that.afterRead({ file: compressImg, content: imgData })
      callback('上传成功')
    })
  },
  mounted() {
    let _that = this
    _that.init()
    // document.getElementById('fileInput').addEventListener('change', () => {
    //   console.log('dfsfdsfds', document.getElementById('fileInput').files)
    //   let selectedFile = document.getElementById('fileInput').files[0]
    //   var reader = new FileReader() //这是核心,读取操作就是由它完成.
    //   reader.readAsText(selectedFile) //读取文件的内容,也可以读取文件的URL
    //   reader.onloadend = function (e) {
    //     let data = e.target.result
    //     let imgData = data.replace(/[\r\n]/g, '')
    //     let arr = imgData.split(',')
    //     let mime = arr[0].match(/:(.*?);/)[1]
    //     let suffix = mime.split('/')[1]
    //     let bstr = atob(arr[1])
    //     let n = bstr.length
    //     let u8arr = new Uint8Array(n)
    //     while (n--) {
    //       u8arr[n] = bstr.charCodeAt(n)
    //     }
    //     let compressImg = new File([u8arr], `${'file'}.${suffix}`, {
    //       type: mime
    //     })
    //     console.log('dfsffsdfsdsfsd===================', compressImg)
    //     _that.afterRead({ file: compressImg, content: imgData })
    //   }
    // })
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.fromPage = from.path
    })
  },
  methods: {
    ...mapMutations('product', ['setField', 'setArrayField', 'addFileInfoId']),
    ...mapMutations('carProduct', ['setObjData', 'setCarIds']),
    ...mapMutations('addCustomer', ['setCustomerData', 'setCustomerIds']),
    ...mapMutations('loading', ['setLoading']),
    init() {
      const title = {
        bank: '银行卡扫描',
        card: '身份证扫描'
      }
      let type = this.$route.query.type
      this.title = title[type]
      this.type = type
    },
    handleColor() {
      let type = this.$route.query.type
      if (
        (this.result !== null &&
          type === 'bank' &&
          this.bankFileList.length > 0) ||
        (this.result !== null &&
          type === 'card' &&
          this.upFileList.length > 0 &&
          this.downFileList.length > 0)
      ) {
        return 'c-fft3q2-bottom-active'
      }
      return ''
    },
    handleBack() {
      this.$dialog
        .confirm({
          title: '此页面信息未保存，确认离开页面吗'
        })
        .then(() => {
          this.$router.go(-1)
        })
        .catch(() => {})
    },
    handleCamera() {
      takeCamera()
    },
    afterRead(file) {
      if (this.type === 'bank') {
        this.bankFileList = []
        this.bankFileList.push(file)
        this.uploadFileBankCard(file.file)
      }
      if (this.type === 'card') {
        if (this.idImageType === 'front') {
          this.upFileList = []
          this.upFileList.push(file)
          this.uploadFileIDCard(this.idImageType, file.file)
        }
        if (this.idImageType === 'back') {
          this.downFileList = []
          this.downFileList.push(file)
          this.uploadFileIDCard(this.idImageType, file.file)
        }
      }

      this.show = false
    },
    uploadFileIDCard(cardSide, files) {
      this.setLoading(true)
      let file = new FormData()
      file.append('cardSide', cardSide)
      file.append('type', this.$route.query.peopleType)
      file.append('files', files)
      API.judgeIDCard(file).then(res => {
        if (res.data && res.data.code === 1000) {
          let dataObj = res.data.data
          for (let i in this.result) {
            this.result[i] = dataObj[i] ? dataObj[i] : this.result[i]
          }
          this.getFileList(dataObj.fileInfoId)
          this.setLoading(false)
          // console.log('dfdfdfdfdfdfdf', this.result)
        } else {
          this.result = null
          this.$message.error(res.data.msg)
          this.setLoading(false)
        }
      })
    },
    uploadFileBankCard(files) {
      this.setLoading(true)
      let file = new FormData()
      file.append('files', files)
      API.judgeBankCard(file).then(res => {
        this.setLoading(false)
        if (res.data && res.data.code === 1000) {
          // this.result = res.data.data
          let dataObj = res.data.data
          for (let i in this.bankInfo) {
            this.bankInfo[i] = dataObj[i] ? dataObj[i] : this.bankInfo[i]
          }
          this.getFileList(dataObj.fileInfoId)
          this.setLoading(false)
        } else {
          this.setLoading(false)
          this.result = null
          this.$message.error(res.data.msg)
        }
      })
    },
    getFileList(id) {
      this.fileInfoIdList.length === 1 &&
        this.type === 'bank' &&
        this.fileInfoIdList.unshift()
      this.fileInfoIdList.length === 2 &&
        this.type === 'card' &&
        this.fileInfoIdList.unshift()
      this.fileInfoIdList.push(id)
    },
    handleClick() {
      let { data, index, type } = this.$route.query
      let resultObj = type == 'card' ? this.result : this.bankInfo
      if (!resultObj.fileInfoId) return false
      this.$router.go(-1)
      if (this.fromPage == '/productOffline') {
        let flag = index !== undefined
        if (flag) {
          for (let i in resultObj) {
            resultObj[i] !== undefined &&
              this.setArrayField([resultObj[i], i, data, index])
            // if (i === 'fileInfoId') {
            //   this.addFileInfoId(resultObj[i])
            // }
            if (i === 'chnName') {
              this.setArrayField([resultObj[i], 'name', data, index])
            }
          }
          this.fileInfoIdList.forEach(item => {
            this.addFileInfoId(item)
          })
        } else {
          for (let i in resultObj) {
            resultObj[i] !== undefined && this.setField([i, resultObj[i]])
            // if (i === 'fileInfoId') {
            //   this.addFileInfoId(resultObj[i])
            // }
            if (i === 'chnName') {
              this.setField(['name', resultObj[i]])
            }
          }
          this.fileInfoIdList.forEach(item => {
            this.addFileInfoId(item)
          })
        }
      }
      if (this.fromPage == '/car') {
        for (let i in resultObj) {
          resultObj[i] !== undefined && this.setObjData([data, i, resultObj[i]])
          if (i === 'chnName') {
            this.setObjData([data, 'name', resultObj[i]])
          }
        }
        this.fileInfoIdList.forEach(item => {
          this.setCarIds(item)
        })
      }
      if (this.fromPage.indexOf('/addCustomer') > -1) {
        for (let i in resultObj) {
          resultObj[i] !== undefined && this.setCustomerData([i, resultObj[i]])
        }
        this.fileInfoIdList.forEach(item => {
          this.setCustomerIds(item)
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
.c-fft3q2 {
  height: 100%;
  background: #fafafa;
  position: relative;
  &-header-left {
    width: 10px;
    height: 18px;
    transform: rotate(180deg);
  }
  &-header-close {
    width: 21px;
    height: 21px;
    margin-left: 5px;
  }
  &-main {
    height: calc(100vh - 38px);
    overflow-y: scroll;
  }
  &-item {
    margin-top: 13px;
    padding: 15px;
    background-color: #fff;
    &-title {
      font-size: 18px;
      color: #000;
      font-weight: bold;
    }
    &-content {
      margin-top: 15px;
      background: #f5f5f5;
      height: 179.5px;
      width: 345px;
      position: relative;
      text-align: center;
      &-img {
        width: 175px;
        height: 106.5px;
        margin-top: 14px;
      }
      &-img-c {
        width: 51.5px;
        height: 51.5px;
        position: absolute;
        top: 42px;
        left: 147px;
      }
      &-text {
        position: absolute;
        bottom: 0;
        background: @c-color-primary;
        height: 45.5px;
        line-height: 45.5px;
        font-size: 17px;
        color: #fff;
        width: 345px;
      }
    }
  }
  &-img-list {
    margin-top: 13px;
    padding: 15px;
    background-color: #fff;
    font-size: 12px;
    color: #999;
    &-title {
      padding-bottom: 15px;
    }
    &-title-txt {
      color: @c-color-primary;
      font-weight: bold;
    }
    &-item {
      margin-left: 21px;
      position: relative;
      &:first-child {
        margin-left: 0;
      }
    }
    &-item-big {
      img {
        width: 70px;
        height: 46px;
      }
    }
    &-item-small {
      img {
        width: 14px;
        height: 14px;
        position: absolute;
        top: 39px;
        left: 28px;
      }
    }
    &-item-txt {
      width: 70px;
      font-size: 10px;
      color: #999;
      text-align: center;
      margin-top: 5px;
    }
  }
  &-bottom {
    position: fixed;
    bottom: 20px;
    left: 15px;
    width: 345px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    background: @c-color-primary;
    opacity: 0.5;
    font-size: 17px;
    color: #fff;
    border-radius: 4.5px;
    &-active {
      opacity: 1;
    }
  }
  &-pop {
    height: 163.5px;
    width: 375px;
    box-sizing: border-box;
    background: #fff;
    padding: 15px;
    border-radius: 13px 13px 0 0;
  }
  &-pop-item {
    font-size: 15px;
    color: #666;
    margin-top: 10px;
    padding-bottom: 10px;
    border-bottom: 0.5px solid #e9e9e9;
    &:last-child {
      border-bottom: none;
      color: @c-color-primary;
    }
    img {
      width: 24px;
      height: 20px;
      margin-right: 10px;
    }
  }
}
.c-lnqk5r {
  margin-top: 15px;
  background: #f5f5f5;
  height: 179.5px;
  width: 345px;
  position: relative;
  text-align: center;
  &-img {
    height: 179.5px;
    width: 345px;
  }
  &-text {
    position: absolute;
    bottom: 0;
    background: @c-color-primary;
    height: 45.5px;
    line-height: 45.5px;
    font-size: 17px;
    color: #fff;
    width: 345px;
    opacity: 0.5;
  }
}
</style>
